<?php
require_once("FileUtil.php");

class ContentExtractor {
		
	public function getContentFromFile($filename) {
		$file_name = $filename;
		$file_handle = fopen($file_name,"r") or die("Coudln't open file"+$file_name);
		$content = fread($file_handle,filesize($file_name)) or die("Couldn't read file"+$file_name);

		return $content;
	}

	public function getRequestVarValue($req_array,$param_name) {
		if(count($req_array)>0) {
			return $req_array[$param_name];
		}
	}
	
	public function getDirectoryContent($dirname) {
		echo "Opening directory $dirname";
		if ($handle = opendir($dirname)) {
		    echo "Directory handle: $handle\n";
		    echo "Image Files:\n";
			
			$files = array();
			
		    /* This is the correct way to loop over the directory. */
		    while (false !== ($file = readdir($handle))) {
				if(is_dir($file) && $file != "." && $file != ".." ) {
				    echo "File Name:" . $file ."\n";
		    		$dir = array("$file" => $this->getDirectoryContent($file));
		    		array_push($files,$dir);
		    	} else if (FileUtil::isAnImage($file)) {
		    		echo "File Name:" . $file ."\n";
		        	array_push($files,$file);
		        }
		    }
		    closedir($handle);
		    return $files;
		}
	}
	
	public function listDirs($where){
		echo "<table border=\"1\"><tr><td><b>Name</b></td><td><b>Type</b></td>";
		echo "<td><b>Invisible (Hidden)?</b></td></tr>";
		    $itemHandler=opendir($where);
		    $i=0;
		    while(($item=readdir($itemHandler)) !== false){
		        if(substr($item, 0, 1)!="."){
		            if(is_dir($item)){
		                echo "<tr><td>$item</td><td>Directory</td><td>No</td></tr>";
		            }else{
		                echo "<tr><td>$item</td><td>File</td><td>No</td></tr>";
		            }
		            $i++;
		        }else{
		            if(is_dir($item)){
		                echo "<tr><td>$item</td><td>Directory</td><td>Yes</td></tr>";
		            }else{
		                echo "<tr><td>$item</td><td>File</td><td>Yes</td></tr>";
		            }
		            $i++;
		        }
		       }
		echo "</table>";
	}
	
	public function listdirRecursive($dir='.') {
		//echo "Opening directory $dir";
	    if (!is_dir($dir)) {
	        return false;
	    }
	   
	    $files = array();
	    $this->listdiraux($dir, $files);
	
	    return $files;
	}

	public function listdiraux($dir, &$files) {
	    $handle = opendir($dir);
	    while (($file = readdir($handle)) !== false) {
	        if ($file == '.' || $file == '..') {
	            continue;
	        }
	        $filepath = $dir == '.' ? $file : $dir . '/' . $file;
	        if (is_link($filepath))
	            continue;
	        if (is_file($filepath))
	            $files[] = $filepath;
	        else if (is_dir($filepath))
	            $this->listdiraux($filepath, $files);
	    }
	    closedir($handle);
	}
		
}


?>